import Server from "@/main/server/Server";
import express from "express";
import path from "node:path";
import multer from "multer";
import { resolve } from "node:path";
import { access, constants, mkdir, readFile, readdir } from "node:fs/promises";

const port = 6363
const modelsPath = resolve(process.cwd(), "./static/models");
const modelJsonName = 'model.json'
const modelWeightsName = 'model.weights.bin'

const router = express.Router();
const storage = multer.diskStorage({
  destination: async function (req, file, cb) {
    const dirPath = path.resolve(process.cwd(), `./static/models/${req.params.modulename}`)
    await access(dirPath, constants.F_OK).catch((err) => mkdir(dirPath, { recursive: true }));

    cb(null, dirPath);
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage });

router.post("/savemodel/:modulename", upload.fields([{ name: modelJsonName, maxCount: 1 }, { name: modelWeightsName, maxCount: 1 }]), async function (req, res) {
  const result = {
    [modelJsonName]: `http://localhost:${port}/models/${req.params.modulename}/${req.files[modelJsonName][0].filename}`,
    [modelWeightsName]: `http://localhost:${port}/models/${req.params.modulename}/${req.files[modelWeightsName][0].filename}`
  };
  res.append("content-type", "application/json");
  res.send(JSON.stringify(result));
});

router.get('/modelsdir', function (req, res) {
  readdir(modelsPath, { recursive: true }).then(dir => {
    if (Array.isArray(dir)) {
      dir = dir.map(path => path.replace('\\', '/'))
    }
    res.send(dir)
  })
})

export default function modelsInit() {
  access(modelsPath, constants.F_OK).catch((err) => mkdir(modelsPath, { recursive: true }));

  const server = new Server(6363, router);
}
